﻿using System;
using System.Linq;
using PmSadis.WebFormsUi.ExpandedControls;
using PmSadis.Repositories.Abstract;
using System.Collections.Generic;
using DevExpress.Web.ASPxGridView;
using System.Drawing;

namespace PmSadis.WebFormsUi.Administrator
{
    public partial class Supports : System.Web.UI.Page
    {
        /// <summary>
        /// Применяем настройки по-умолчанию для грида
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Init(object sender, EventArgs e)
        {
            gvSupport.SetDefaultSettings();
        }

        /// <summary>
        /// Репозиторий для сообщений техподдержки
        /// </summary>
        private IListRepository<PmSadis.Models.Support> _repo;

        public Supports()
        {
            _repo = new PmSadis.Repositories.SupportRepository();
        }

        /// <summary>
        /// Получить все сообщения
        /// </summary>
        /// <returns></returns>
        public IQueryable<PmSadis.Models.SupportFoAdmin> GetAll()
        {
            return _repo.All.Select(x => new PmSadis.Models.SupportFoAdmin
            {
                SupportId=x.SupportId,
                DateCreate=x.DateCreate,
                Title=x.Title,
                Content=x.Content,
                Status = x.IsComplete ? 2 : (x.IsOnControl ? 1 : 0)
            }).OrderBy(x=>x.Status);
        }

        /// <summary>
        /// Удалить сообщение
        /// </summary>
        /// <param name="supportId">Идентификатор сообщения</param>
        public void DeleteSupport(int supportId)
        {
            _repo.Delete(supportId);
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            var keys = gvSupport.GetSelectedFieldValues("SupportId").Select(x=>Convert.ToInt32(x)).ToList();
            if (keys.Count() == 0) return;

            keys.ForEach(x => _repo.Delete(x));
            gvSupport.DataBind();
        }

        protected void btnOnControl_Click(object sender, EventArgs e)
        {
            var keys = gvSupport.GetSelectedFieldValues("SupportId").Select(x=>Convert.ToInt32(x)).ToList();
            if (keys.Count() == 0) return;

            SetOnControlForMany(keys);

            gvSupport.DataBind();
            gvSupport.Selection.UnselectAll();
        }
        /// <summary>
        /// Задать статус "На контроле" для списка сообщений техподдержки
        /// </summary>
        /// <param name="keys"></param>
        private void SetOnControlForMany(List<int> keys)
        {
            var result = _repo.All.Where(x => keys.Contains(x.SupportId)).ToList();
            result.ForEach(x =>
            {
                x.IsOnControl = true;
                x.IsComplete = false;
                _repo.Edit(x);
            });
        }

        protected void btnOnComplete_Click(object sender, EventArgs e)
        {
            var keys = gvSupport.GetSelectedFieldValues("SupportId").Select(x => Convert.ToInt32(x)).ToList();
            if (keys.Count() == 0) return;

            SetCompleteForMany(keys);

            gvSupport.DataBind();
            gvSupport.Selection.UnselectAll();
        }
        /// <summary>
        /// Задать статус "Завершено" для списка сообщений техподдержки
        /// </summary>
        /// <param name="keys"></param>
        private void SetCompleteForMany(List<int> keys)
        {
            var result = _repo.All.Where(x => keys.Contains(x.SupportId)).ToList();
            result.ForEach(x =>
            {
                x.IsOnControl = true;
                x.IsComplete = true;
                _repo.Edit(x);
            });
        }

        protected void btnCancelAll_Click(object sender, EventArgs e)
        {
            var keys = gvSupport.GetSelectedFieldValues("SupportId").Select(x => Convert.ToInt32(x)).ToList();
            if (keys.Count() == 0) return;

            CancellAllForMany(keys);

            gvSupport.DataBind();
            gvSupport.Selection.UnselectAll();
        }
        /// <summary>
        /// Сбросить статусы для списка сообщений техподдержки
        /// </summary>
        /// <param name="keys"></param>
        private void CancellAllForMany(List<int> keys)
        {
            var result = _repo.All.Where(x => keys.Contains(x.SupportId)).ToList();
            result.ForEach(x =>
            {
                x.IsOnControl = false;
                x.IsComplete = false;
                _repo.Edit(x);
            });
        }

        protected void gvSupport_HtmlRowPrepared(object sender, ASPxGridViewTableRowEventArgs e)
        {
            if (e.RowType != GridViewRowType.Data) return;

            var status = gvSupport.GetRowValuesByKeyValue(e.KeyValue, "Status");
            if (Equals(status, 2))
                e.Row.CssClass+= " support-complete-row";
            else if(Equals(status, 1))
                e.Row.CssClass+= " support-on-control-row";
        }
    }
}